#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#  Copyright (c) Huoty - All rights reserved
# 
#      Author: Huoty <sudohuoty@gmail.com>
#  CreateTime: 2016-11-14 10:32:49
# *************************************************************

from tornado import gen
from tornado.ioloop import IOLoop
from tornado.queues import Queue

q = Queue(maxsize=3)
#q = Queue()

@gen.coroutine
def consumer():
    while True:
        item = yield q.get()
        try:
            print('Doing work on %s' % item)
            yield gen.sleep(0.01)
        finally:
            q.task_done()

@gen.coroutine
def producer():
    for item in range(5):
        yield q.put(item)
        print('Put %s' % item)

@gen.coroutine
def main():
    # Start consumer without waiting (since it never finishes).
    IOLoop.current().spawn_callback(consumer)
    yield producer()     # Wait for producer to put all tasks.
    print("---------------> tags")
    yield q.join()       # Wait for consumer to finish all tasks.
    print('Done')


# Script starts from here

IOLoop.current().run_sync(main)

#如上代码, 初看, 能懂它的大概意思, 但是具体一行一行看下来, 它的执行顺序就不是很清楚了, 下面是我的一些理解
#1. 进入 main
#2. consumer 派生一个回调, 在那里等待
#3. producer 协程, 不断进入又出来( 我所理解的协程: 不断进入, 不断出来 )
#4. q.join 协程, 卡住

